import { Injectable, Logger } from '@nestjs/common'
import { InjectEntityManager, InjectRepository } from '@nestjs/typeorm'
import Redis from 'ioredis'

import { isNil } from 'lodash'

import { EntityManager, Repository } from 'typeorm'

import { InjectRedis } from '~/common/decorators/inject-redis.decorator'
import { paginate } from '~/helper/paginate'

import { Pagination } from '~/helper/paginate/pagination'
import { UserSosQueryDto, UserSosUpdateDto } from './userSos.dto'
import { UserSosEntity } from './userSos.entity'

@Injectable()
export class UserSosService {
  private logger = new Logger(UserSosService.name)

  constructor(
    @InjectRedis() private readonly redis: Redis,
    @InjectRepository(UserSosEntity)
    private userSosRepository: Repository<UserSosEntity>,
    @InjectEntityManager() private entityManager: EntityManager,
  ) { }

  /**
   * 呼救查询
   * @param queryDto
   */
  async listSos(queryDto: UserSosQueryDto): Promise<Pagination<UserSosEntity>> {
    const { page, pageSize, userId, uid, status, deptId } = queryDto
    const queryBuilder = await this.userSosRepository
      .createQueryBuilder('data')
      .leftJoinAndSelect('data.user', 'user')
      .select(['data.id', 'data.userId', 'data.uid', 'data.times', 'data.status', 'data.startAt', 'data.endAt', 'user.deptId', 'user.nickname'])
      .where({
        ...(!isNil(status) && { status }),
        ...(uid && { uid }),
        user: {
          ...(userId && { id: userId }),
          ...(deptId && { deptId }),
        },
      })
      // .andWhere({
      //   ...((time && time[0]) && { startAt: MoreThanOrEqual(time[0]) }),
      // })
      // .andWhere({
      //   ...((time && time[1]) && { startAt: LessThanOrEqual(time[1]) }),
      // })
      .orderBy('data.startAt', 'DESC')
    // this.logger.debug('queryBuilder', queryBuilder.getQueryAndParameters())
    return paginate<UserSosEntity>(queryBuilder, {
      page,
      pageSize,
    })
  }

  async findOne({ userId, uid, status }: UserSosQueryDto): Promise<UserSosEntity> {
    const info = await this.userSosRepository
      .createQueryBuilder('sos')
      .where({
        ...(!isNil(userId) ? { userId } : null),
        ...(uid ? { uid } : null),
        ...(!isNil(status) ? { status } : null),
      })
      .getOne()
    return info
  }

  /**
   * 呼救数据保存
   * @param data
   */
  async saveSos(data: UserSosEntity) {
    await this.userSosRepository.save(data)
  }

  /**
   * 呼救数据更新
   * @param id
   * @param data
   */
  async updateSos(id: number, { ...data }: UserSosUpdateDto) {
    await this.userSosRepository.update(id, data)
  }

  /**
   * 呼救数据删除
   * @param id
   */
  async deleteSos(id: number) {
    await this.userSosRepository.delete(id)
  }
}
